﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using thinger.VisionModels;
using thinger.VisitionDAL;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace thinger.VisionDemo
{
    public partial class Frmformul : Form
    {
        public Frmformul(SysConfig sysConfig)
        {
            InitializeComponent();
            this.sysConfig = sysConfig;
            //---- 初始化
            this.Load += Frmformul_Load;
        }
        private readonly SysConfig sysConfig = null;
        //取料拍照
        private List<RobotData> QUDatas = new List<RobotData>();
        private string QUPath = Application.StartupPath + "\\Robot\\quliao";

        //OK下料
        private List<RobotData> OKDatas = new List<RobotData>();
        private string OKPath = Application.StartupPath + "\\Robot\\OK_xialiao";

        //NG下料
        private List<RobotData> NGDatas = new List<RobotData>();
        private string NGPath = Application.StartupPath + "\\Robot\\NG_xialiao";

        //临时工单
        private List<OrderData> TempDatas = new List<OrderData>();

        private void Frmformul_Load(object sender, EventArgs e)
        {
            load_init();
            if (GlobalVar.Instance.QUDatas == null)
            {
                AddLog(1, "取料加载失败！");
            }
            else
            {
                AddLog(0, "取料加载成功！");
            }
            if (GlobalVar.Instance.OKDatas == null)
            {
                AddLog(1, "OK加载失败！");
            }
            else
            {
                AddLog(0, "OK加载成功！");
            }

            if (GlobalVar.Instance.NGDatas == null)
            {
                AddLog(1, "NG加载失败！");
            }
            else
            {
                AddLog(0, "NG加载成功！");
            }
        }

        private void btn_Add_Click(object sender, EventArgs e)
        {
            var btn = sender as Button;
            //Console.WriteLine(btn.Name+"：按下");
            if (btn.Name == "btn_Add_qu")
            {
                this.QUDatas.Add(new RobotData()
                {
                    RobotX = Convert.ToSingle(this.num_robotX_qu.Value),
                    RobotY = Convert.ToSingle(this.num_robotY_qu.Value),
                    RobotZ = Convert.ToSingle(this.num_robotZ_qu.Value),
                    RobotR = Convert.ToSingle(this.num_robotR_qu.Value),
                });
                RefreshData(qu_Data, QUDatas);
            }

            if (btn.Name == "btn_Add_ok")
            {
                this.OKDatas.Add(new RobotData()
                {
                    RobotX = Convert.ToSingle(this.num_robotX_ok.Value),
                    RobotY = Convert.ToSingle(this.num_robotY_ok.Value),
                    RobotZ = Convert.ToSingle(this.num_robotZ_ok.Value),
                    RobotR = Convert.ToSingle(this.num_robotR_ok.Value),
                });

                RefreshData(ok_Data, OKDatas);
            }

            if (btn.Name == "btn_Add_ng")
            {
                this.NGDatas.Add(new RobotData()
                {
                    RobotX = Convert.ToSingle(this.num_robotX_ng.Value),
                    RobotY = Convert.ToSingle(this.num_robotY_ng.Value),
                    RobotZ = Convert.ToSingle(this.num_robotZ_ng.Value),
                    RobotR = Convert.ToSingle(this.num_robotR_ng.Value),
                });

                RefreshData(ng_Data, NGDatas);
            }
        }
        //-- 初始化
        private void load_init()
        {
            string path = string.Empty;
            if (sysConfig.GetQUliaoPath != string.Empty)
            {
                this.cmb_qu.Items.Clear();
                var list_ = GetAllRobotModels(QUPath);

                if (list_.Count > 0)
                {
                    this.cmb_qu.Items.AddRange(list_.ToArray());
                    if (!list_.Exists(s => s == sysConfig.GetQUliaoPath))
                    {
                        this.cmb_qu.SelectedIndex = 0;
                    }
                    else
                        this.cmb_qu.SelectedIndex = list_.FindIndex(s => s == sysConfig.GetQUliaoPath);
                    path = QUPath + "\\" + this.cmb_qu.Text.Trim() + "\\config.ini";
                    QUDatas = JsonHelper.JSONToEntity<List<RobotData>>(IniConfigHelper.ReadIniData("生产配方", "拍照抓取", "", path));
                    GlobalVar.Instance.QUDatas = QUDatas;
                    RefreshData(qu_Data, QUDatas);
                }

            }

            if (sysConfig.GetOKliaoPath != string.Empty)
            {
                this.cmb_ok.Items.Clear();
                var list_ = GetAllRobotModels(OKPath);

                if (list_.Count > 0)
                {
                    this.cmb_ok.Items.AddRange(list_.ToArray());
                    if (!list_.Exists(s => s == sysConfig.GetOKliaoPath))
                    {
                        this.cmb_ok.SelectedIndex = 0;
                    }
                    else
                        this.cmb_ok.SelectedIndex = list_.FindIndex(s => s == sysConfig.GetOKliaoPath);
                    path = OKPath + "\\" + this.cmb_ok.Text.Trim() + "\\config.ini";
                    OKDatas = JsonHelper.JSONToEntity<List<RobotData>>(IniConfigHelper.ReadIniData("生产配方", "OK下料", "", path));
                    GlobalVar.Instance.OKDatas = OKDatas;
                    RefreshData(ok_Data, OKDatas);
                }
            }

            if (sysConfig.GetNGliaoPath != string.Empty)
            {
                this.cmb_ng.Items.Clear();
                var list_ = GetAllRobotModels(NGPath);

                if (list_.Count > 0)
                {
                    this.cmb_ng.Items.AddRange(list_.ToArray());
                    if (!list_.Exists(s => s == sysConfig.GetNGliaoPath))
                    {
                        this.cmb_ng.SelectedIndex = 0;
                    }
                    else
                        this.cmb_ng.SelectedIndex = list_.FindIndex(s => s == sysConfig.GetNGliaoPath);
                    path = NGPath + "\\" + this.cmb_ng.Text.Trim() + "\\config.ini";
                    NGDatas = JsonHelper.JSONToEntity<List<RobotData>>(IniConfigHelper.ReadIniData("生产配方", "NG下料", "", path));
                    GlobalVar.Instance.NGDatas = NGDatas;
                    RefreshData(ng_Data, NGDatas);
                }
            }
        }
        #region 刷新列表
        //-------------- 刷新列表


        private void RefreshData(DataGridView d, List<RobotData> data)
        {
            d.DataSource = null;
            d.DataSource = data;
            d.Columns[0].HeaderText = "坐标X";
            d.Columns[1].HeaderText = "坐标Y";
            d.Columns[2].HeaderText = "坐标Z";
            d.Columns[3].HeaderText = "坐标R";
            d.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
        }


        //-------------- 刷新列表

        public List<string> GetListDates(string basePath)
        {
            List<string> result = new List<string>();

            DirectoryInfo directoryInfo = new DirectoryInfo(basePath);

            foreach (var item in directoryInfo.GetDirectories())
            {
                result.Add(item.Name);
            }
            return result;
        }

        #endregion

        private void btn_Del_Click(object sender, EventArgs e)
        {
            var btn = sender as Button;
            if (btn.Name == "btn_Del_qu")
            {
                if (this.qu_Data.SelectedRows.Count > 0)
                {
                    int index = this.qu_Data.SelectedRows[0].Index;

                    this.QUDatas.RemoveAt(index);

                    RefreshData(qu_Data, QUDatas);
                }
                else
                {
                    AddLog(1, "请先选中要删除的数据");
                }
            }

            if (btn.Name == "btn_Del_ok")
            {
                if (this.ok_Data.SelectedRows.Count > 0)
                {
                    int index = this.ok_Data.SelectedRows[0].Index;

                    this.OKDatas.RemoveAt(index);


                    RefreshData(ok_Data, OKDatas);
                }
                else
                {
                    AddLog(1, "请先选中要删除的数据");
                }
            }

            if (btn.Name == "btn_Del_ng")
            {
                if (this.ng_Data.SelectedRows.Count > 0)
                {
                    int index = this.ng_Data.SelectedRows[0].Index;

                    this.NGDatas.RemoveAt(index);
                    RefreshData(ng_Data, NGDatas);
                }
                else
                {
                    AddLog(1, "请先选中要删除的数据");
                }
            }
        }

        private void btn_Update_Click(object sender, EventArgs e)
        {
            var btn = sender as Button;
            if (btn.Name == "btn_Update_qu")
            {
                if (this.qu_Data.SelectedRows.Count > 0)
                {
                    int index = this.qu_Data.SelectedRows[0].Index;

                    this.QUDatas[index].RobotX = Convert.ToSingle(this.num_robotX_qu.Value);
                    this.QUDatas[index].RobotY = Convert.ToSingle(this.num_robotY_qu.Value);
                    this.QUDatas[index].RobotZ = Convert.ToSingle(this.num_robotZ_qu.Value);
                    this.QUDatas[index].RobotR = Convert.ToSingle(this.num_robotR_qu.Value);
                    RefreshData(qu_Data, QUDatas);
                }
                else
                {
                    AddLog(1, "请先选中要更新的数据");
                }
            }

            if (btn.Name == "btn_Update_ok")
            {
                if (this.ok_Data.SelectedRows.Count > 0)
                {
                    int index = this.ok_Data.SelectedRows[0].Index;

                    this.OKDatas[index].RobotX = Convert.ToSingle(this.num_robotX_ok.Value);
                    this.OKDatas[index].RobotY = Convert.ToSingle(this.num_robotY_ok.Value);
                    this.OKDatas[index].RobotZ = Convert.ToSingle(this.num_robotZ_ok.Value);
                    this.OKDatas[index].RobotR = Convert.ToSingle(this.num_robotR_ok.Value);

                    RefreshData(ok_Data, OKDatas);
                }
                else
                {
                    AddLog(1, "请先选中要更新的数据");
                }
            }

            if (btn.Name == "btn_Update_ng")
            {
                if (this.ng_Data.SelectedRows.Count > 0)
                {
                    int index = this.ng_Data.SelectedRows[0].Index;

                    this.NGDatas[index].RobotX = Convert.ToSingle(this.num_robotX_ng.Value);
                    this.NGDatas[index].RobotY = Convert.ToSingle(this.num_robotY_ng.Value);
                    this.NGDatas[index].RobotZ = Convert.ToSingle(this.num_robotZ_ng.Value);
                    this.NGDatas[index].RobotR = Convert.ToSingle(this.num_robotR_ng.Value);

                    RefreshData(ng_Data, NGDatas);
                }
                else
                {
                    AddLog(1, "请先选中要更新的数据");
                }
            }


        }

        private void btn_Clear_Click(object sender, EventArgs e)
        {
            var btn = sender as Button;
            if (btn.Name == "btn_Clear_qu")
            {
                //this.qu_Data.Rows.Clear();
            }
            if (btn.Name == "btn_Clear_ok")
            {
                //this.ok_Data.Rows.Clear();
            }
            if (btn.Name == "btn_Clear_ng")
            {
                //this.ng_Data.Rows.Clear();
            }
        }


        private void btn_Save_common_Click(object sender, EventArgs e)
        {

            var btn = sender as Button;
            string path = string.Empty;
            string Sava_path = string.Empty;
            string MSGstr = string.Empty;
            if (btn.Name == "btn_Save_qu")
            {
                if (this.txt_quName.Text.Trim().Length == 0)
                {
                    MessageBox.Show("保存数据不能为空", "保存点阵");
                    return;
                }

                path = QUPath + "\\" + this.txt_quName.Text.Trim();
                MSGstr = "拍照抓取点阵";


            }

            if (btn.Name == "btn_Save_ok")
            {
                if (this.txt_okName.Text.Trim().Length == 0)
                {
                    MessageBox.Show("保存数据不能为空", "保存点阵");
                    return;
                }
                path = OKPath + "\\" + this.txt_okName.Text.Trim();
                MSGstr = "OK下料点阵";
            }

            if (btn.Name == "btn_Save_ng")
            {
                if (this.txt_ngName.Text.Trim().Length == 0)
                {
                    MessageBox.Show("保存数据不能为空", "保存点阵");
                    return;
                }
                path = NGPath + "\\" + this.txt_ngName.Text.Trim();
                MSGstr = "NG下料点阵";
            }



            //判断
            //文件夹路径
            //如果包含，删除
            if (Directory.Exists(path))
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(path);
                directoryInfo.Delete(true);
            }
            //创建文件夹
            Directory.CreateDirectory(path);
            Sava_path = path + "\\config.ini";
            bool result = false;
            if (btn.Name == "btn_Save_qu")
            {
                result = IniConfigHelper.WriteIniData("生产配方", "拍照抓取", JsonHelper.EntityToJSON(QUDatas), Sava_path);
            }
            if (btn.Name == "btn_Save_ok")
            {
                result = IniConfigHelper.WriteIniData("生产配方", "OK下料", JsonHelper.EntityToJSON(OKDatas), Sava_path);
            }
            if (btn.Name == "btn_Save_ng")
            {
                result = IniConfigHelper.WriteIniData("生产配方", "NG下料", JsonHelper.EntityToJSON(NGDatas), Sava_path);
            }
            if (result == false)
            {
                AddLog(1, MSGstr + "数据写入失败！");
                MessageBox.Show(MSGstr + "数据写入失败！");


            }
            else
            {
                AddLog(0, MSGstr + "数据写入成功！");
                MessageBox.Show(MSGstr + "数据写入成功！");
            }

        }







        private void cmb_ModelList_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 获取所有的模板
        /// </summary>
        /// <param name="basePath"></param>
        /// <returns></returns>
        public List<string> GetAllRobotModels(string basePath)
        {
            List<string> result = new List<string>();

            DirectoryInfo directoryInfo = new DirectoryInfo(basePath);

            foreach (var item in directoryInfo.GetDirectories())
            {
                result.Add(item.Name);
            }
            return result;
        }

        private void btn_RefreshShapeModel_Click(object sender, EventArgs e)
        {
            this.cmb_qu.Items.Clear();
            var list = GetAllRobotModels(QUPath);

            if (list.Count > 0)
            {
                this.cmb_qu.Items.AddRange(list.ToArray());
                this.cmb_qu.SelectedIndex = 0;
            }
        }

        private void btn_LoadShapeModel_Click(object sender, EventArgs e)
        {
            //string path = RobotBasePath + "\\" + this.cmb_ModelList.Text.Trim();

            //var result = shapeModel.LoadShapeModel(path);

            //if (result.IsSuccess)
            //{
            //    this.matchParams = result.Content1;
            //    this.circleParams = result.Content2;
            //    AddLog(0, "模板加载成功：" + this.cmb_ModelList.Text.Trim());
            //}
            //else
            //{
            //    AddLog(1, "模板加载失败");
            //}
        }


        #region 添加日志
        /// <summary>
        /// 当前时间
        /// </summary>
        private string CurrentTime
        {
            get { return DateTime.Now.ToString("HH:mm:ss"); }
        }

        /// <summary>
        /// 添加日志信息
        /// </summary>
        /// <param name="index">日志等级</param>
        /// <param name="log">日志信息</param>
        public void AddLog(int index, string log)
        {

        }




        #endregion

        private void button17_Click(object sender, EventArgs e)
        {

        }

        private void button10_Click(object sender, EventArgs e)
        {

        }

        private void btn_RefreshShapeModel_Click_1(object sender, EventArgs e)
        {

        }

        private void btn_LoadShapeModel_Click_1(object sender, EventArgs e)
        {

        }

        private void button_cmb_Fresh_Click(object sender, EventArgs e)
        {
            string tempPath = string.Empty;

            var btn = sender as Button;
            if (btn.Name == "btn_Fresh_qu")
            {
                this.cmb_qu.Items.Clear();
                var list_ = GetAllRobotModels(QUPath);

                if (list_.Count > 0)
                {
                    this.cmb_qu.Items.AddRange(list_.ToArray());
                    this.cmb_qu.SelectedIndex = 0;
                }

            }

            if (btn.Name == "btn_Fresh_ok")
            {
                this.cmb_ok.Items.Clear();
                var list_ = GetAllRobotModels(OKPath);

                if (list_.Count > 0)
                {
                    this.cmb_ok.Items.AddRange(list_.ToArray());
                    this.cmb_ok.SelectedIndex = 0;
                }
            }

            if (btn.Name == "btn_Fresh_ng")
            {
                this.cmb_ng.Items.Clear();
                var list_ = GetAllRobotModels(NGPath);

                if (list_.Count > 0)
                {
                    this.cmb_ng.Items.AddRange(list_.ToArray());
                    this.cmb_ng.SelectedIndex = 0;
                }
            }
        }

        private void btn_Load_ng_Click(object sender, EventArgs e)
        {
            string tempPath = string.Empty;
            string MSGstr = string.Empty;
            string path = string.Empty;
            var btn = sender as Button;
            if (btn.Name == "btn_Load_qu")
            {
                MSGstr = "拍照抓取点阵";
                if (this.cmb_qu.Text.Trim() == string.Empty)
                {
                    AddLog(1, MSGstr + "数据加载失败！");
                    MessageBox.Show(MSGstr + "数据加载失败！");
                    return;
                }

                path = QUPath + "\\" + this.cmb_qu.Text.Trim() + "\\config.ini";
                QUDatas = JsonHelper.JSONToEntity<List<RobotData>>(IniConfigHelper.ReadIniData("生产配方", "拍照抓取", "", path));
                GlobalVar.Instance.QUDatas = QUDatas;
                RefreshData(qu_Data, QUDatas);
                this.sysConfig.GetQUliaoPath = path;


            }

            if (btn.Name == "btn_Load_ok")
            {
                MSGstr = "OK下料点阵";

                if (this.cmb_ok.Text.Trim() == string.Empty)
                {
                    AddLog(1, MSGstr + "数据加载失败！");
                    MessageBox.Show(MSGstr + "数据加载失败！");
                    return;
                }

                path = OKPath + "\\" + this.cmb_ok.Text.Trim() + "\\config.ini";
                OKDatas = JsonHelper.JSONToEntity<List<RobotData>>(IniConfigHelper.ReadIniData("生产配方", "OK下料", "", path));
                GlobalVar.Instance.OKDatas = OKDatas;
                RefreshData(ok_Data, OKDatas);
                this.sysConfig.GetOKliaoPath = path;
            }

            if (btn.Name == "btn_Load_ng")
            {
                MSGstr = "NG下料点阵";
                if (this.cmb_ng.Text.Trim() == string.Empty)
                {
                    AddLog(1, MSGstr + "数据加载失败！");
                    MessageBox.Show(MSGstr + "数据加载失败！");
                    return;
                }

                path = NGPath + "\\" + this.cmb_ng.Text.Trim() + "\\config.ini";
                NGDatas = JsonHelper.JSONToEntity<List<RobotData>>(IniConfigHelper.ReadIniData("生产配方", "NG下料", "", path));
                GlobalVar.Instance.NGDatas = NGDatas;
                RefreshData(ng_Data, NGDatas);
                this.sysConfig.GetNGliaoPath = path;
            }


            //写入配置
            if (this.sysConfig != null)
            {
                string info = JsonHelper.EntityToJSON(this.sysConfig);

                bool result = IniConfigHelper.WriteIniData("系统配置", "系统配置", info, Application.StartupPath + "\\config.ini");

                if (result)
                {
                    MessageBox.Show("系统配置保存成功", "保存配置");
                }
                else
                {
                    MessageBox.Show("系统配置保存失败：INI写入失败", "保存配置");
                }

            }
            else
            {
                MessageBox.Show("系统配置保存失败：请检查参数", "保存配置");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void qu_Data_Click(object sender, EventArgs e)
        {
            if (this.qu_Data.SelectedRows.Count > 0)
            {
                int index = this.qu_Data.SelectedRows[0].Index;

                this.num_robotX_qu.Text = this.QUDatas[index].RobotX.ToString();
                this.num_robotY_qu.Text = this.QUDatas[index].RobotY.ToString();
                this.num_robotZ_qu.Text = this.QUDatas[index].RobotZ.ToString();
                this.num_robotR_qu.Text = this.QUDatas[index].RobotR.ToString();
            }
            else
            {
                AddLog(1, "请先选中要删除的数据");
            }
        }

        private void ok_Data_Click(object sender, EventArgs e)
        {
            if (this.ok_Data.SelectedRows.Count > 0)
            {
                int index = this.ok_Data.SelectedRows[0].Index;

                this.num_robotX_ok.Text = this.OKDatas[index].RobotX.ToString();
                this.num_robotY_ok.Text = this.OKDatas[index].RobotY.ToString();
                this.num_robotZ_ok.Text = this.OKDatas[index].RobotZ.ToString();
                this.num_robotR_ok.Text = this.OKDatas[index].RobotR.ToString();
            }
            else
            {
                AddLog(1, "请先选中要删除的数据");
            }
        }

        private void ng_Data_Click(object sender, EventArgs e)
        {
            if (this.ng_Data.SelectedRows.Count > 0)
            {
                int index = this.ng_Data.SelectedRows[0].Index;

                this.num_robotX_ng.Text = this.NGDatas[index].RobotX.ToString();
                this.num_robotY_ng.Text = this.NGDatas[index].RobotY.ToString();
                this.num_robotZ_ng.Text = this.NGDatas[index].RobotZ.ToString();
                this.num_robotR_ng.Text = this.NGDatas[index].RobotR.ToString();
            }
            else
            {
                AddLog(1, "请先选中要删除的数据");
            }
        }








    






        private void txt_dama_x_A_1_KeyPress(object sender, KeyPressEventArgs e)
        {
            base.OnKeyPress(e);

            // 允许退格键
            if (e.KeyChar == (char)Keys.Back)
                return;

            // 正则表达式：只允许数字和小数点
            if (!Char.IsControl(e.KeyChar) && !Regex.IsMatch(e.KeyChar.ToString(), @"^[\d.]*$"))
            {
                e.Handled = true; // 不允许输入
            }
        }


    }
}
